<template>
  <div>
    <loader :loading="loading">
      <!-- 加载页面 -->
      <template #loader>
        <div>
          <zombie></zombie>
        </div>
      </template>
      <!-- 内容页面 -->
      <template #body>
        <!-- 首页图片 -->
        <el-image class="background-image animate-[header-effect_2s]"
                  :src="albumPoster"
                  @click="albumItems = albumItemsASync"
                  fit="cover">
          <template #error>
            <div class="image-slot background-image-error"></div>
          </template>
        </el-image>
        <!-- 首页文字 -->
        <div class="signature-wall flex justify-center items-center animate-[hideToShow_0.7s] absolute top-0 w-full h-full">
          <h1 class="playful">
            <span v-for="(a, index) in albumTitle" :key="index">{{a}}</span>
          </h1>
          <div class="printer cursor-pointer" @click="getGuShi()">
            <printer :printerInfo="printerInfo">
              <template #paper="scope">
                <h3>
                  {{ scope.content }}<span class="cursor">|</span>
                </h3>
              </template>
            </printer>
          </div>
          <input v-if="route.query.type === 'web'" 
                 v-model="webType.url" 
                 @keydown.enter="getWeb"
                 class="webUrlInput">
          <div id="bannerWave1"></div>
          <div id="bannerWave2"></div>
          <i class="el-icon-arrow-down" @click="navigation('.page-container-wrap')"></i>
        </div>
        <div v-show="albumContent" class="page-container-content">
            <div class="aurora-content" v-html="albumContent"></div>
        </div>
        <!-- Aurora首页内容 -->
        <div v-if="!route.query.type" class="page-container-wrap">
          <div ref="grid" class="grid grid-album">
            <div v-for="(item, index) in albumItems" 
                 :key="item.picUrl"   
                 @click="item?.click && item.click($event)" 
                 class="grid-item grid-item-album" 
                 :href="item" 
                 target="_blank"
                 :overtip="`+ ${albumItems.length-9}`"
                 :data-sub-html="albumItems[index]?.note?`<a target=_blank href=/album?type=aurora&id=${articles[index].id}>${albumItems[index]?.note}</a>`:'NO NOTE'"
                 data-fb-html='是否需要添加评论功能呢？'
                 :data-src="item.picUrl">
                <div class="imgbox relative overflow-hidden flex rounded-14px">
                  <div class="imgAlt">
                    {{albumItems[index]?.note}}
                  </div>
                  <img target="_blank" 
                       :title="albumItems[index]?.note"  
                       onerror="this.src='https://cdn.seovx.com/d/?mom=302'" 
                       class="lazyload_images" 
                       :data-src="item.picUrl" 
                       v-lazy="checkImage(item,index)" 
                       alt="">
                </div>
                <span @click.stop="routerAurora(articles[index].id)">{{item?.note}}</span>
              </div>
            <div class="grid-sizer"></div>
          </div>
          <div class="pagination-wrap">
            <div v-if="pagination.total !== articles.length" 
                 @click="pageArticles()" 
                 class="pagination">
              下一页
            </div>
            <div v-else class="select-none">
              ~~到底啦~~
            </div>
          </div>
        </div>
        <!-- 图片列表 -->
        <div v-if="route.query.type" class="page-container-wrap">
          <div ref="grid" class="grid">
            <a v-for="(item, index) in albumItems"  
               :key="item.picUrl" 
               class="grid-item" 
               :href="checkImage(item,index)" 
               target="_blank"
               :overtip="`+ ${albumItems.length-9}`"
               :data-sub-html="item?.note||item.picUrl"
               @click="item?.click && item.click($event)"
               @mouseenter="item?.mouseOn && item.mouseOn()" 
               data-fb-html='是否需要添加评论功能呢？'>
                <div class="imgbox relative overflow-hidden flex rounded-14px">
                  <div class="imgAlt">
                    {{item?.note}}
                  </div>
                  <img target="_blank" 
                       :title="item?.note" 
                       onerror="this.src='https://agentestudio.com/uploads/post/image/69/main_how_to_design_404_page.png'" 
                       class="lazyload_images" 
                       v-lazy="checkImage(item,index)"   
                       alt="">
                </div>
            </a>
            <div class="grid-sizer"></div>
        </div>
        <div class="pagination-wrap">
          <div v-if="pagination.total !== articles.length" 
               @click="pageArticles()" 
               class="pagination">
            下一页
          </div>
          <div v-else class="select-none">
            ~~到底啦~~
          </div>
        </div>
        </div>
        <!-- Footer now handled by PageLayout -->
      </template>
    </loader>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick, inject } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useMainStore } from '../store';
import { ElMessage } from 'element-plus';
import Masonry from 'masonry-layout';
import imagesLoaded from 'imagesloaded';
import sourceHandle from '../utils/sourceHandle';
import loader from "./common/loader.vue";
import zombie from "./common/zombie.vue";
import printer from "./common/printer.vue";
// Footer now handled by PageLayout
import jmcomic from '../assets/json/jmcomiccity.json';

// 注入依赖
const http = inject('$http');
const common = inject('$common');
const constant = inject('$constant');

// 路由
const route = useRoute();
const router = useRouter();

// DOM引用
const grid = ref(null);

// store
const store = useMainStore();

// 响应式状态
const loading = ref(false);
const albumLoading = ref(true);
const showAside = ref(true);
const albumTitle = ref("动态相册");
const albumPoster = ref(constant.two_poem_image[0]);
const printerInfo = ref("你看对面的青山多漂亮");
const pagination = reactive({
  current: 1,
  size: 30,
  total: 0,
  keywords: ""
});
const guShi = reactive({
  "content": "",
  "origin": "",
  "author": "",
  "category": ""
});
const options = reactive({
  gutter: 10,
  columnWidth: '.grid-item',
  itemSelector: '.grid-item',
  percentPosition: true,
});
const webType = reactive({
  url: route.query.url || "https://www.roginx.ink/v/daily_picture.html" || "https://www.evacg.cc/"
});
const articles = ref([]);
const albumItems = ref([]);
const albumItemsASync = ref([]);
const albumContent = ref(undefined);
const masonry = ref(null);
const dynamicGallery = ref(undefined);
const secret = ref("");

// 路由映射
const routerMap = {
  "aurora": getAurora,
  "acg": getRandom,
  "web": getWeb,
  "dynamic": getDynamic,
  "origin": getOrigin
};

// 监听路由变化
watch(() => route.query, (newQuery, oldQuery) => {
  albumItems.value.length = 0;
  getGuShi();
  pagination.size = route.query.type ? 10 : 30;
  
  if (!route.query.type) {
    getArticles();
  } else {
    try {
      routerMap[route.query.type]("");
    } catch (error) {
      ElMessage({
        message: "错误的路由!",
        type: "error"
      });
    }
  }
}, { immediate: true });

// 方法
function checkImage(item, index) {
  let src = item.picUrl;
  let note = item.note;
  
  if (note?.slice(0, 4) == "NSFW" && !route.query.NSFW) {
    return 'https://gd-hbimg.huaban.com/9d4628a3c336c8c816366d7f8b6a7937cd2b3b74c9bd4-KYmhYR_fw658webp';
  } else {
    return src?.indexOf('qiniu.roginx.ink') != -1 ? src + '-album' : src;
  }
}

function reInitGallery() {
  nextTick(() => {
    try {
      window.dynamicGallery?.destroy();
    } catch (error) {
      console.error("Gallery destroy error:", error);
    }
    
    if (window.lightGallery && grid.value) {
      window.dynamicGallery = window.lightGallery(grid.value, {
        plugins: [
          window.lgHash, 
          window.lgRotate, 
          window.lgVideo, 
          window.lgZoom, 
          window.lgFullscreen, 
          window.lgAutoplay, 
          window.lgComment
        ],
        mode: 'lg-slide',
        cssEasing: 'ease',
        commentBox: true,
        fbComments: true,
        galleryId: 1,
        speed: 300
      });
    }
  });
}

function checkPicture() {
  albumLoading.value = true;
  let masonryInterval;
  
  if (grid.value) {
    masonry.value = new Masonry(grid.value, options);
    reInitGallery();
    
    masonryInterval = setInterval(() => {
      masonry.value.layout();
      
      masonry.value.getItemElements().forEach((item) => {
        const img = item.querySelector('img');
        if (img) {
          if (!img.complete) {
            img.onload = () => {
              if (img.naturalWidth < 160 || img.naturalHeight < 100) {
                if (route.query.type) masonry.value.remove(item);
              }
            };
          } else if (img.naturalWidth < 160 || img.naturalHeight < 100) {
            if (route.query.type) masonry.value.remove(item);
          }
        }
      });
    }, 1250);
    
    // 监听图片加载完成事件，重新布局
    imagesLoaded(grid.value, () => {
      masonry.value = new Masonry(grid.value, options);
      albumLoading.value = false;
      reInitGallery();
    });
  }
}

function pageArticles() {
  pagination.current = pagination.current + 1;
  
  if (!route.query.type) {
    getArticles();
  } else {
    try {
      routerMap[route.query.type]();
    } catch (error) {
      ElMessage({
        message: "错误的路由!",
        type: "error"
      });
    }
  }
}

async function getOrigin() {
  let list = [];
  let objList = [];
  const newHost = new URL(jmcomic.bookSourceUrl).host;
  
  if (!route.query.keywords) {
    setTimeout(() => {
      ElMessage({
        message: "你知道嘛，你误入歧途了！我不打算给你返回任何内容~",
        type: "error"
      });
    }, 1000);
    return;
  }
  
  try {
    const res = await sourceHandle.ruleSearch(jmcomic, route.query.keywords);
    list = sourceHandle.selector(res, jmcomic.ruleSearch.bookList);
    
    list[0].toArray().forEach((item, index) => {
      objList.push(sourceHandle.getBookPreview($(item), jmcomic.ruleSearch));
    });
    
    let obj = objList.map((image) => {
      return {
        note: image.name,
        picUrl: image.coverUrl?.replace(window.location.host, newHost),
        click: (e) => {
          let url = jmcomic.contentUrl?.replace("${id}", image.id);
          const newUrl = router.resolve({
            path: '/album',
            query: {
              type: 'web',
              url: url,
              selector: jmcomic.ruleContent.items,
              decodeImage: true,
            }
          }).href;
          window.open(newUrl, '_blank');
        }
      };
    });
    
    albumItems.value = obj;
    setTimeout(() => {
      checkPicture();
    }, 1000);
  } catch (error) {
    console.error("获取Origin内容失败:", error);
    ElMessage({
      message: error.message || "获取内容失败",
      type: "error"
    });
  }
}

async function getWeb() {
  albumTitle.value = "网页图片加载中...";
  
  try {
    const response = await fetch(`/api/scrape?url=${encodeURIComponent(webType.url)}`, {
      method: 'GET',
    });
    
    const html = await response.text();
    albumItems.value = [];
    
    const cleanHtml = html?.replace(/<script.*?<\/script>/gs, '');
    const doc = $(cleanHtml);
    let obj = [];
    const newHost = new URL(webType.url).host;
    
    if (route.query.selector) {
      let images = sourceHandle.attr(doc, route.query.selector);
      obj = images.toArray().map((item, index) => {
        return {
          note: item,
          picUrl: item?.replace(window.location.host, newHost),
          decodeImage: route.query.decodeImage,
          decode: function(isEnd) {
            if (albumItems.value[index].decodeImage != "true") return;
            sourceHandle.decodeImage(item, function(newImage) {
              albumItems.value[index].decodeImage = false;
              albumItems.value[index].picUrl = newImage;
              if (albumItems.value[index + 1]) {
                albumItems.value[index + 1].decode(albumItems.value.length == index + 1);
              }
              checkPicture();
            });
          }
        };
      });
    } else {
      const images = doc.find("img").toArray();
      obj = images.map((image) => {
        let src = $(image)?.attr("data-original") || image.src;
        return {
          note: image.alt,
          picUrl: src?.replace(window.location.host, newHost)
        };
      });
    }
    
    albumTitle.value = doc.filter('title').text();
    albumPoster.value = obj[Math.floor(obj.length / 2)]?.picUrl || constant.two_poem_image[0];
    albumItems.value = obj;
    
    if (albumItems.value[0]?.decode) {
      albumItems.value[0].decode();
    }
    
    setTimeout(() => {
      checkPicture();
    }, 1000);
  } catch (error) {
    console.error("获取Web内容失败:", error);
    ElMessage({
      message: error.message || "获取内容失败",
      type: "error"
    });
  }
}

function getRandom() {
  albumTitle.value = "网页图片加载中...";
  
  const count = route.query.num || 20;
  let obj = new Array(parseInt(count));
  
  for (let index = 0; index < obj.length; index++) {
    obj[index] = {
      picUrl: route.query.api || constant.ACGAPI[route.query.cannel || 0] + "?id=" + index,
      note: "这是随机图片"
    };
  }
  
  albumTitle.value = "随机二次元图片";
  albumPoster.value = route.query.api || constant.ACGAPI[route.query.cannel || 0];
  albumItems.value = obj;
  
  setTimeout(() => {
    checkPicture();
  }, 1000);
}

async function getAurora() {
  albumTitle.value = "网页图片加载中...";
  
  try {
    const res = await http.get(`/aurora/get/work/pt/${route.query.id}`);
    
    if (!common.isEmpty(res)) {
      document.title = res.title;
      albumTitle.value = res.title;
      albumContent.value = res.content;
      
      let items = JSON.parse(res.picture);
      let obj = [];
      obj.push(...items[0].map((picUrl, index) => ({ 
        picUrl: picUrl, 
        note: items[1][index]
      })));
      
      albumItems.value = obj;
      albumPoster.value = res.poster;
      checkPicture();
      
      if (res.content?.match(/playlist=(\d+)/)) {
        store.pushPlaylist(res.content.match(/playlist=(\d+)/)[1]);
      }
    }
  } catch (error) {
    console.error("获取Aurora内容失败:", error);
    ElMessage({
      message: error.message || "获取内容失败",
      type: "error"
    });
  }
}

async function getArticles() {
  try {
    const res = await http.get(`/aurora/search/works/pt?type=1&point=pt&start=${(pagination.current-1)*pagination.size}&num=${pagination.size}&keys=${pagination.keywords}`);
    
    if (!common.isEmpty(res)) {
      albumTitle.value = "图册集";
      articles.value = articles.value.concat(res[0].filter(item => item.adm === 0));
      pagination.total = res[1].total;
      
      let obj = articles.value.map(article => {
        return {
          picUrl: article.poster,
          note: article.title
        };
      });
      
      albumItems.value = obj;
      checkPicture();
    }
  } catch (error) {
    console.error("获取文章列表失败:", error);
    ElMessage({
      message: error.message || "获取内容失败",
      type: "error"
    });
  }
}

function getDynamic() {
  if (!secret.value) {
    secret.value = prompt("请输入密码（可以猜一猜😀", "");
  }
  
  if (secret.value != "3612") {
    ElMessage({
      message: "密码错误啦!我将对你进行传送😆！",
      type: "error"
    });
    
    setTimeout(() => {
      window.location.href = `/album?type=aurora&id=196`;
    }, 3000);
    return;
  }
  
  http.post(constant.baseURL + "/diary/listArticle", pagination)
    .then((res) => {
      if (!common.isEmpty(res.data)) {
        albumTitle.value = "动态相册";
        articles.value = articles.value.concat(res.data.records);
        pagination.total = res.data.total;
        
        let obj = [];
        articles.value.forEach(artcile => {
          let items = JSON.parse(artcile.articleItems);
          obj.push(...items[0].map((picUrl, index) => ({ 
            picUrl: picUrl, 
            note: items[1][index]
          })));
        });
        
        albumItems.value = obj;
        checkPicture();
      }
    })
    .catch((error) => {
      ElMessage({
        message: error.message || "获取内容失败",
        type: "error"
      });
    });
}

function navigation(selector) {
  let pageId = document.querySelector(selector);
  window.scrollTo({
    top: pageId.offsetTop,
    behavior: "smooth"
  });
}

function getGuShi() {
  const xhr = new XMLHttpRequest();
  xhr.open('get', constant.jinrishici);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      Object.assign(guShi, JSON.parse(xhr.responseText));
      printerInfo.value = guShi.content;
    }
  };
  xhr.send();
}

function routerAurora(auroraId) {
  router.push({ 
    path: '/album', 
    query: { ...route.query, id: auroraId, type: 'aurora' } 
  });
}
</script>

<style scoped>
.page-container-content {
  @apply bg-[var(--background)] p-25px-15px mt-[-3px];
}

.page-container-content .aurora-content {
  @apply m-auto max-w-800px;
}

.grid {
  @apply flex flex-wrap ml-10px bg-[var(--background)] animate-[zoomIn_0.8s_ease-in-out];
}

.webUrlInput {
  @apply outline-none border-none text-[rgba(255,255,255,0.75)] text-center bg-none text-20px whitespace-nowrap overflow-hidden text-ellipsis tracking-1px w-300px p-t-20px p-x-8px p-b-8px transition-all duration-300 border-b-3px border-b-transparent;
}

.webUrlInput:hover,
.webUrlInput:focus {
  @apply text-white left-0 border-b-3px border-b-white;
}

.grid.loadding .grid-item {
  @apply opacity-0 animate-[zoomIn_0.8s_ease-in-out];
}

.grid-item {
  @apply animate-[zoomIn_0.8s_ease-in-out] block absolute w-[calc(20%_-_10px)] cursor-zoom-in mb-12px min-w-100px min-h-80px overflow-hidden;
}

.grid-item-album {
  @apply bg-none !important;
}

.grid-item-album span:hover {
  @apply text-[var(--themeBackground)] transition-all duration-300;
}

.grid-item-album span {
  @apply transition-all duration-300 cursor-pointer mt-6px mb-15px leading-20px block text-[var(--fontColor)];
}

.grid-item .imgAlt {
  @apply cursor-pointer absolute w-full h-full flex justify-center items-center text-center opacity-0 bg-[var(--mask)] text-white pointer-events-none transition-all duration-300;
}

.grid-item:hover .imgAlt {
  @apply opacity-100 transition-all duration-300;
}

.grid-item img {
  @apply bg-[var(--lightGray)] w-full h-full;
}

.grid-sizer {
  @apply w-[20%];
}

.signature-wall {
  @apply flex flex-col relative select-none h-screen overflow-hidden;
}

.playful {
  @apply text-[var(--white)] text-40px;
}

.printer {
  @apply text-[var(--white)] bg-[var(--translucent)] rounded-10px pl-10px pr-10px;
}

#bannerWave1 {
  @apply h-84px bg-[var(--bannerWave1)] absolute w-[200%] bottom-0 z-10 animate-[gradientBG_120s_linear_infinite];
}

#bannerWave2 {
  @apply h-100px bg-[var(--bannerWave2)] absolute w-[400%] bottom-0 z-5 animate-[gradientBG_120s_linear_infinite];
}

.cursor {
  @apply ml-1px animate-[hideToShow_0.7s_infinite] font-200;
}

.el-icon-arrow-down {
  @apply text-40px font-bold text-[var(--white)] absolute bottom-60px animate-[my-shake_1.5s_ease-out_infinite] z-15 cursor-pointer;
}

.page-container-wrap {
  @apply bg-[var(--background)] relative transition-all duration-500;
}

.pagination-wrap {
  @apply flex justify-center mt-40px;
}

.pagination {
  @apply p-y-13px p-x-15px border border-[var(--lightGray)] rounded-3rem text-[var(--greyFont)] w-100px select-none cursor-pointer text-center;
}

.pagination:hover {
  @apply border-[var(--themeBackground)] text-[var(--themeBackground)] shadow-[0_0_5px_var(--themeBackground)];
}

@media screen and (max-width: 768px) {
  .grid-item {
    @apply w-[calc(50%_-_10px)];
  }
  .grid-sizer {
    @apply w-[50%];
  }
  h1 {
    @apply text-35px;
  }
}

/* 添加UnoCSS兼容样式 */
.animate-header-effect-2s {
  @apply animate-[header-effect_2s];
}

.animate-hideToShow {
  @apply animate-[hideToShow_0.7s];
}

.my-center {
  @apply flex justify-center items-center;
}

.rounded-14px {
  @apply rounded-14px;
}

.bg-background {
  @apply bg-[var(--background)];
}
</style>